<script>
import { FormFieldMap, SettingComponents } from '@src/component/form/components';

import * as Utils from '@src/component/form/util';
import { isEmpty } from '@src/util/type'
import { MultiFieldNames, searchProduct, searchCustomer } from './common.js';

import SearchProductSelect from '@src/modules/task/components/list/SearchProductSelect.vue';
import SearchCustomerSelect from '@src/modules/task/components/list/SearchCustomerSelect.vue';
import { setBaseDistValue } from '@src/util/addressUtil';
export default {
  name: 'batch-form',
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: 'create',
    },
    list: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: 0,
    },
    columnNum: {
      type: Number,
      default: 1,
    },
    item: {
      type: Number | String | Object,
      default: '',
    },
  },
  data: () => {
    return {
      selectedField: {},
      form: {},
      userList: [],
      customer: {},
      product: {},
    };
  },
  watch: {
    item(v) {
      this.customizeParams();
    },
    fields(v) {
      if (isEmpty(this.form)) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
    this.customizeParams();
  },
  methods: {
    // 初始化表单
    initForm() {
      if (Object.keys(this.form).length) return;
      this.fields.forEach(f => {
        const isMulti = Utils.isMultiField(f);
        if (!this.form[f.fieldName] || !this.form[f.fieldName].length) {
          // 地址的默认值初始化为对象
          let tv = '';
          const ArrayFormType = [
            'date',
            'datetime',
            'area',
            'cascader',
            'related_customers',
          ];
          const ObjectFormType = ['customerAddress', 'address', 'link'];

          if (ObjectFormType.includes(f.formType)) {
            tv = {};
          }
          if (
            ArrayFormType.includes(f.formType) ||
            (MultiFieldNames.includes(f.fieldName) && isMulti)
          ) {
            if (f.formType === 'user' && !isMulti) return;
            tv = [];
          }

          this.form[f.fieldName] = tv;
        }
      });
    },

    // 回显表单
    customizeParams() {
      if (this.item && this.item.fieldName) {
        const {
          fieldName,
          content,
          formType,
          id,
          ids,
        } = this.item;
        const types = [
          'level',
          'serviceContent',
          'serviceType',
          'paymentMethod',
          'onceException',
          'allotTypeStr',
          'state',
          'cascader',
        ];
        // 用户相关的fieldName or formType
        const userCate = [
          'createUser',
          'allotUser',
          'executor',
          'synergyId',
          'user',
        ];

        this.inputValueReset(fieldName);

        if (
          userCate.includes(fieldName) ||
          userCate.includes(formType)
        ) {
          if (ids) {
            this.form[fieldName] = ids;
            ids.forEach((item, i) => {
              this.userList.push({
                id: item,
                name: Array.isArray(content)
                  ? content[i]
                  : content.split('，')[i],
              });
            });
          } else if (id) {
            this.form[fieldName] = id;
            this.userList = [{ id, name: content }];
          }
        } else if (
          types.includes(fieldName) ||
          types.includes(formType)
        ) {
          this.form[fieldName] = content.split('，');
        } else if (fieldName === 'tlmName' || fieldName === 'linkmanId') {
          this.form[fieldName] = id;
          this.userList = [{ id, name: content }];
        } else if (formType === 'datetime' || formType === 'date') {
          this.form[fieldName] = content.split('-');
        } else if (fieldName === 'customer') {
          this.form[fieldName] = id;
          this.customer = { name: content, value: id };
        } else if (fieldName === 'product') {
          this.form[fieldName] = id;
          this.product = { name: content, value: id };
        } else if (fieldName === 'tags') {
          this.form[fieldName] = [];
          ids &&
            ids.forEach((item, i) => {
              this.form[fieldName].push({
                id: item,
                tagName: content.split('，')[i],
              });
            });
        } else if (fieldName === 'area') {
          this.form[fieldName] = setBaseDistValue(this.item);
        } else if (
          !this.item.isSystem &&
          formType === 'select' &&
          this.item.setting &&
          !this.item.setting.isMulti
        ) {
          this.form[fieldName] = content.split('，');
        } else {
          this.form[fieldName] = content;
        }
      } else {
        this.selectedField = {};
        this.form = {};
      }
    },

    // 返回数据
    returnData() {
      return Object.assign({}, this.form);
    },

    update(event, action) {
      this.form = {};
      if (action === 'tags') {
        return (this.form.tags = event.map(item => {
          return item;
        }));
      }

      if (action === 'dist') {
        return (this.form.area = event);
      }
      const f = event.field;
      this.form[f.fieldName] = event.newValue;
      this.$forceUpdate();
    },
    
    // 根据fieldName 重置对应的form value
    inputValueReset(fieldName) {
      this.selectedField = this.fields.filter(f => f.fieldName === fieldName)[0];
      if (this.selectedField.isSystem && this.item.operatorValue) {
        // 系统字段回显operator，自定义字段不需要回显
        this.selectedField.operatorValue = this.item.operatorValue;
      }
      const isMulti = Utils.isMultiField(this.selectedField);

      if (this.selectedField.formType === 'date') {
        this.form[fieldName] = [];
      } else {
        this.form[fieldName] = fieldName == 'tags' ? [] : this.form[fieldName] || '';
      }
      if (MultiFieldNames.includes(this.selectedField.fieldName) && isMulti) {
        this.form[fieldName] = [];
      }
      if (
        this.selectedField.formType === 'select' &&
        !this.selectedField.isSystem &&
        !isMulti
      ) {
        this.form[fieldName] = [];
      }
    },

    changeOperator() {
      this.selectedField.operator = this.selectedField.operatorValue;
    },

    // 渲染表单字段名 key
    renderSelector() {
      if (!this.fields) return null;

      return (
        <el-select
          value={this.selectedField.fieldName}
          onChange={this.inputValueReset}
          filterable
        >
          {this.fields.map(f => (
            <el-option
              key={f.fieldName}
              label={f.displayName}
              value={f.fieldName}
            />
          ))}
        </el-select>
      );
    },

    // 渲染条件
    renderOperateSelect() {
      if (!this.selectedField.operatorOptions) return;

      return (
        <el-select
          value={this.selectedField.operatorValue}
          onInput={value => (this.selectedField.operatorValue = value)}
          onChange={this.changeOperator}
        >
          {this.selectedField.operatorOptions.map(operatorItem => (
            <el-option
              key={operatorItem.value}
              label={operatorItem.label}
              value={operatorItem.value}
            />
          ))}
        </el-select>
      );
    },

    // 渲染表单字段值 value
    renderInput(h) {
      const f = this.selectedField;
      const comp = FormFieldMap.get(f.formType);
      const multiple = Utils.isMultiField(f);

      // 此处拓展客户模块自定义筛选的字段
      if (
        !comp &&
        f.formType !== 'tags' &&
        f.formType !== 'area' &&
        f.formType !== 'linkman'
      ) {
        return null;
      }

      if (MultiFieldNames.includes(f.fieldName)) {
        if (f.setting) {
          f.setting.isMulti = multiple;
        } else {
          f.setting = { isMulti: multiple };
        }
      }

      if (f.formType === 'select') {
        f.setting.isMulti = false;
      }

      let childComp = null;
      let value = this.form[f.fieldName];

      if (f.fieldName == 'customer') {
        childComp = h('search-customer-select', {
          props: {
            placeholder: '请选择客户',
            field: f,
            value: value ? [{ label: this.customer.name || '', value }] : [],
            remoteMethod: searchCustomer,
          },
          on: {
            input: event => {
              this.form = {};
              this.customer = event && event.length > 0 ? event[0] : {};
              this.form[f.fieldName] = this.customer.id;
            },
          },
        });
      } else if (f.fieldName == 'product') {
        childComp = h('search-product-select', {
          props: {
            placeholder: '请选择产品',
            field: f,
            value: value ? [{ label: this.product.name || '', value }] : [],
            remoteMethod: searchProduct,
          },
          on: {
            input: event => {
              this.form = {};
              this.product = event && event.length > 0 ? event[0] : {};
              this.form[f.fieldName] = this.product.id;
            },
          },
        });
      } else if (f.formType === 'user') {
        childComp = h('user-search', {
          props: {
            multiple,
            field: f,
            value,
            disableMap: true,
            userList: this.userList,
          },
          on: {
            update: event => this.update(event),
            input: event => {
              if (event && event.length > 1) {
                this.$set(this, 'product', event[0]);
              }
              // this.form[f.fieldName] = event.keyword;
            },
          },
        });
      } else if (f.fieldName === 'tags') {
        childComp = h('biz-team-select', {
          props: {
            multiple,
            value: value ? value : [],
          },
          on: {
            input: event => this.update(event, 'tags'),
          },
        });
      } else if (f.formType === 'area') {
        childComp = h('base-dist', {
          props: {
            value: value || [],
            showDefaultCountry: false
          },
          on: {
            input: event => this.update(event, 'dist'),
          },
        });
      } else if (f.fieldName === 'tlmName' || f.formType === 'linkman') {
        childComp = h('linkman-search', {
          props: {
            field: f,
            value,
            disableMap: true,
            userList: this.userList,
          },
          on: {
            update: event => this.update(event),
          },
        });
      } else if (f.formType === 'related_customers') {
        childComp = h('customer-search', {
          props: {
            field: f,
            value,
            disableMap: true,
            multiple: true,
          },
          on: {
            update: event => this.update(event),
          },
        });
      } else {
        childComp = h(
          comp.extend && comp.extend[`${f.formType}_search`]
            ? comp.extend[`${f.formType}_search`]
            : comp.build,
          {
            props: {
              field: f,
              value,
              disableMap: true,
              placeholder: Utils.genPlaceholder(f),
              seo: true,
              // toggle: true,
            },
            on: {
              update: event => this.update(event),
            },
          }
        );
      }
      return h(
        'form-item',
        {
          props: {
            label: f.displayName,
            needValidate: false,
          },
        },
        [childComp]
      );
    },
  },
  render(h) {
    const operateDom =
      this.list.length - 1 === this.index ? (
        <div
          class={
            this.selectedField.fieldName
              ? 'task-font14 task-c13 task-inquire-add task-ml15 task-pointer'
              : 'task-font14 task-c13 task-inquire-add task-pointer'
          }
          onClick={() => {
            this.$emit('add');
          }}
        >
          添加
        </div>
      ) : (
        <i
          class="iconfont icon-shanchu1 task-pointer task-ml15 task-icon"
          onClick={() => {
            this.$emit('del', {
              index: this.index,
              v: this.selectedField,
            });
          }}
        />
      );

    return (
      <div>
        {this.item ? (
          <div
            class={
              this.columnNum === 2 ? 'task-flex task-ai task-mt12' : 'task-mt12'
            }
          >
            <div
              class={
                this.columnNum === 2
                  ? 'task-inquire-operator-select task-type'
                  : 'task-mt12 task-type'
              }
            >
              {this.renderSelector()}
            </div>
            <div
              class={
                this.columnNum === 2
                  ? 'task-inquire-operator-select task-type'
                  : 'task-mt12 task-type'
              }
            >
              {this.renderOperateSelect()}
            </div>
            <div
              class={
                this.columnNum === 2
                  ? 'task-inquire-two task-flex task-ai'
                  : 'task-inquire task-flex task-ai'
              }
            >
              {this.renderInput(h)}
              {this.type !== 'view' ? operateDom : ''}
            </div>
          </div>
        ) : null}
      </div>
    );
  },
  components: {
    ...SettingComponents,
    [SearchProductSelect.name]: SearchProductSelect,
    [SearchCustomerSelect.name]: SearchCustomerSelect,
  },
};
</script>

<style lang="scss" scoped>
.task-type {
  width: 210px !important;
  .el-select {
    width: 100%;
  }
}
.task-inquire,
.task-inquire-two {
  margin-top: 12px;
  label {
    display: none !important;
  }
  .form-item {
    width: 210px;
  }
  .form-item-control {
    width: 210px;
    flex: inherit;
    .err-msg-wrap {
      min-height: 0 !important;
      padding-bottom: 0 !important;
    }
  }
}
.task-inquire-add {
  width: 68px;
  height: 32px;
  @include backgroundColorPrimaryLight9();
  border-radius: 4px;
  border: 1px solid $color-primary-light-2;
  @include borderColorPrimaryLight9();
  text-align: center;
  line-height: 32px;
}
.task-inquire-two {
  margin: 0;
  margin-left: 12px;
}
.batch-editing-customer-dialog {
  .base-modal-body {
    padding: 10px 30px 0;
  }

  .item {
    display: flex;
    justify-content: space-between;
    line-height: 32px;
    div {
      flex-grow: 1;
      .el-select {
        width: 100%;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}

.task-inquire-operator-select {
  margin-left: 12px;
}
</style>
